<?php
/**
 * Created by JetBrains PhpStorm.
 * User: cgp
 * Date: 13-4-12
 * Time: 上午9:47
 * To change this template use File | Settings | File Templates.
 */

use pft\Prod\Sale;
use \pft\Prod\Sync;
class PriceDev {
    private $pid;
    private $soap;

    /**
     * @param $pid 产品表ID
     */
    public function __construct($pid) {
        if(empty($pid)) {
            return false;
        }
        $this->pid = $pid;
        $this->soap = SoapInit::GetSoapInside();
    }

    /**
     * 产品价格配置
     *   接口说明：
     *        1).供应商产品动态价格插入或修改(商品总表ID，开始日期，结束日期，
     *              供应价，零售价，类型(0平日1周末2特殊)，记录模式[0插入1修改2修改]，
     *              记录ID[修改状态下需要，记录模式为2时代表映射ID]，价格说明，日库存)
     *        2).In_Dynamic_Price_Merge($pid, $startdate='', $enddate='',
     *                  $g_price=0, $l_price=0, $ptype=0, $mode=0,
     *               $rid=0, $memo='', $ondays=''，$storage='')
     *  update:
     *      1).2013年9月29日11:38:01——添加“日库存”字段
     *      2).2013年10月8日15:35:08——去除获取分销id操作，
     *
     * @param $pid 商品总表ID
     * @param string $startdate 开始日期
     * @param string $enddate 结束日期
     * @param int $g_price 供应价
     * @param int $l_price 零售价
     * @param int $ptype 类型(0平日1周末2特殊)
     * @param int $rid 记录ID[修改状态下需要]
     * @param string $memo 价格说明
     * @param string $ondays 星期
     * @param SoapClient $soap SOAP依赖注入
     * @param string $storage 日库存 -1不限量0售罄
     * @param integer $pft_rflex_id 票付通产品ID（同步产品）
     * @param \Soap $soap16u 16u的SOAP实例
     * @param bool $debug 调试模式
     * @return mixed
     */
    static function DynamicPriceStatic($pid, $startdate='', $enddate='',
        $g_price=0, $l_price=0, $ptype=0, $rid=0, $memo='', $ondays='',
        SoapClient $soap, $storage=-1, $pft_rflex_id=0, $soap16u=null,
        $debug=false,$sync_id=0, $sync_status=0)
    {
        $mode = $rid > 0 ? 1 : 0;
        if($debug) {
            echo 'pid=',$pid,'st=', $startdate,'et=', $enddate, 'gp=', $g_price;
            echo 'lp=',$l_price, 'pt=' ,$ptype,'md=', $mode, 'rid=',$rid,
            'memo=',$memo, 'ondays=',$ondays,"storage=",$storage;
        }
        if($mode==1) {
            $str = "SELECT ptype,start_date,end_date,memo,weekdays,l_price,"
               ."s_price,n_price,storage FROM uu_product_price WHERE id={$rid} LIMIT 1";
            $GLOBALS['le']->query($str);
            $priceData = $GLOBALS['le']->fetch_assoc();
            // $apply_did = 0;
            $newData = array(
                'ptype'      => $ptype,
                'start_date' => $startdate,
                'end_date'   => $enddate,
                'memo'       => $memo,
                'weekdays'   => $ondays,
                'l_price'    => $l_price,
                'storage'    => $storage
            );
            if($ptype) {
                $new_data['s_price'] = $g_price;
            }
            else {
                $newData['n_price']  = $g_price;
            }
            $ctype = ($g_price > $priceData['n_price']
                || $g_price > $priceData['s_price']) ? 3 : 4;
            $changeDate = array_diff_uassoc($newData , $priceData,
             function($a, $b){
                if ($a === $b) {
                    return 0;
                }
                return ($a > $b)? 1:-1;
            });
             $oldData = array_intersect_ukey( $priceData, $changeDate,
             function($key1, $key2){
                if ($key1 == $key2)
                    return 0;
                else if ($key1 > $key2)
                    return 1;
                else
                    return -1;
            });
            pft\Verify\Verify::LogVerify($pid, $_SESSION['memberID'], serialize($oldData),
                serialize($changeDate),'',$ctype);
        }

        $res = $soap->In_Dynamic_Price_Merge($pid, $startdate, $enddate,
            $g_price, $l_price, $ptype, $mode, $rid, $memo, $ondays, $storage);
        //TODO::更新分销平台价格配置
//        file_put_contents('price.log', date('Y-m-d H:i:s') . '|fx_price_change_begin' . PHP_EOL, FILE_APPEND);

        if ($res==100 && ($pft_rflex_id>0 || $sync_status==1)) {
            $fx_mode = $mode==1 ? 2 : 0;
            $soapArr = \Sync::GetMulSoap();

            //新增价格获取主键ID
            if($mode==0) {
                $sql_get_priceid = "SELECT id FROM uu_product_price"
                    ." WHERE pid=$pid AND ptype=$ptype AND "
                    ." start_date='$startdate' AND end_date='$enddate' LIMIT 1";

                $GLOBALS['le']->query($sql_get_priceid);
                $GLOBALS['le']->fetch_assoc();
                $rid = $GLOBALS['le']->f('id');
            }

            //旧的数据
            if ( $pft_rflex_id>0 ) {
                $sale = new Sale($GLOBALS['le'], Sale::SALEID);
                $priceSeted = $sale->GetPriceSet($pid);
                $g_price += $priceSeted[$pid];
                $res2 = $soapArr['trans_soap']->In_Dynamic_Price_Merge($pft_rflex_id, $startdate,
                    $enddate, $g_price, $l_price, $ptype, $fx_mode, $rid, $memo,
                    $ondays, $storage);
            }
            elseif($sync_status==1 && $sync_id>0 && count($changeDate)) {
                $dbArr   = \Sync::GetMulDB();
                //TODO::更新
                if ($mode ==1) {
                    \Sync::LogSync('uu_product_price', $pid, $sync_id, $oldData,
                        $changeDate, $dbArr['trans_le']);
                    $action = 'update';
                } else {
                    //TODO::新增
                    $action = 'create';
                }
                $ret_trans = $soapArr['trans_soap']->In_Dynamic_Price_Merge($sync_id, $startdate,
                    $enddate, $g_price, $l_price, $ptype, $fx_mode, $rid, '',
                    $ondays, $storage, 11);
                if($ret_trans==100) {
                    $where = "tbname='uu_product_price' AND col_id={$pid}";
                    \Sync::ChgSyncStatus($dbArr['trans_le'],0, 1, 0, $where);
                    \Sync::writeLog(\Sync::now() . "|pid={$pid},tid={$sync_id}", \Sync::LOG_DIR . "{$action}_pft_price.log");
                } else {
                    \Sync::writeLog(\Sync::now() . "|pid={$pid},tid={$sync_id}", \Sync::LOG_DIR . "{$action}_pft_price.err");
                }
            }
        }
        if($debug) {
            echo  'res=' . $res;
        }
        return $res;
    }
    /**
     * 价格规则获取
     * 调用接口说明：1).[综合]动态价格获取（产品ID，日期，模式[0XML 1单个价格]，
     *                  开始时间，结束时间，类型[0供应价 1零售价,2最低价]，
     *                  是否需要获取库存1需要）
     *                  说明：时间段价格$date,$mode必须为默认空值并会跨时间集
     *             2).public function get_Dynamic_Price_Merge($pid, $date='',
     *                                  $mode=0, $sdate='', $edate='', $ptype=0，
     *                                $get_storage=0)
     * 使用说明：
     *    当最后一个参数$all=true时，表示获取线路产品主产品及附属产品（票类）的价格规则，
     *      目前线路产品的附属产品仅为儿童票；
     *    当线路的票类不止儿童票时，此函数需更新
     *    update time:2013年6月26日15:57:18
     *    update time:2013年9月30日15:12:26——新增$get_storage参数
     *
     * @param $date 日期
     * @param int $mode   0返回一个判定完成有效日期结算价，1返回所有有效日期记录的XML
     * @param string $sdate   开始时间
     * @param string $edate   结束时间
     * @param integer $ptype  类型[0供应价 1零售价,2最低价]
     * @param integer $get_storage 是否获取库存
     * @param integer $pid 产品（uu_products）id
     * @return mixed
     */
    public function GetDynamicPrice($date, $mode=1, $sdate='', $edate='',
                                    $ptype=0, $get_storage=1, $pid=0)
    {
        if(is_null($this->soap)) {
            $this->soap = \SoapInit::GetSoapInside();
        }
        $pid = $this->pid==-1 ? $pid : $this->pid;
        $result = $this->soap->get_Dynamic_Price_Merge($pid,$date,
            $mode, $sdate, $edate, $ptype, $get_storage);
        if(is_null($this->soap)) {
            var_dump($result);
        }
        return $result;
    }

    /**
     * 实时库存查询
     * @param SoapClient $soap
     * @param integer $tid 商品tid
     * @param integer $dtype 查询类别（1每日实时库存2实时总库存）
     * @param string $times 查询时间串逗号分割
     *                      （例如：2013-09-20,2013-09-21[类别为1时需要]]
     * @param string $nowdate 总库存启用时间[类别为2时需要]
     * @return mixed
     */
    static function GetStorage(SoapClient $soap, $tid, $dtype, $times=null,
                               $nowdate=null) {
        $res = $soap->Dynamic_Storage_Check($tid, $dtype, $times, $nowdate);
        return $res;
    }

    /**
     * 变更总库存
     *
     * @param resource $l mysql实例
     * @param integer $s 库存量
     * @param string $t 启用时间（date('Y-m-d)格式）
     * @param $tid 票类id
     * @param $pid 产品id
     * @return integer 1成功0失败
     */
    static function SetTotalStorage($l, $s, $t, $tid, $pid) {
        $str1 = "SELECT storage,storage_open FROM uu_jq_ticket WHERE id=$tid LIMIT 1";
//        echo $str1;
        $l->query($str1);
        $oldData = $l->fetch_assoc();
        if(count($oldData)) {
            $str = "UPDATE uu_jq_ticket SET storage=$s,storage_open='$t' "
                ."WHERE id=$tid LIMIT 1";
            $l->query($str);
            $ctype = 5;//类型：修改库存
            $newData = array('storage'=>$s,'storage_open'=>$t);
            \pft\Verify\Verify::LogVerify($pid, 0, serialize($oldData),
                serialize($newData),'',$ctype);
            return 1;
        }
        return 0;
    }


    /**
     * 获取指定日期门票零售价
     *
     * @param string $date 日期
     * @param integer $mode 模式
     * @return mixed
     */
    public function GetBuyTicketPriceStorage($date,$mode=1){
        $soap = SoapInit::GetSoapInside();
        $chk = "SELECT l.p_type,l.attribute FROM uu_land l,uu_jq_ticket t"
            ." WHERE t.pid={$this->pid} AND t.landid=l.id";
        $GLOBALS['le']->query($chk);
        $GLOBALS['le']->fetch_assoc();
        if($GLOBALS['le']->f('p_type')=='F') {
            $package = json_decode($GLOBALS['le']->f('attribute'));
            foreach($package as $p){
                $p_storage = $this->getDayStorage($soap, $date, $p->pid);
                if($p_storage < $p->num) {
                    $storage = 0;
                    break;
                } else {
                    $storage = $p_storage;
                }
            }
        }
        else {
            $storage = $this->getDayStorage($soap, $date);
        }
        $dp = $this->GetDynamicPrice($date,$mode,'','',1);
        //echo $storage;
        return array('price'=>$dp/100, 'storage'=>$storage);
    }

    /**
     * 根据日期获取实时库存
     *
     * @param SoapClient $s
     * @param $begintime 日期
     * @param $pid 产品ID
     * @return int|string
     */
    public function getDayStorage(SoapClient $s,$begintime, $pid=null){

        $pid = !empty($pid) ? $pid : $this->pid;

        $str_i = "SELECT id as tid,storage,storage_open FROM uu_jq_ticket "
                ."WHERE pid={$pid} LIMIT 1";
        $GLOBALS['le']->query($str_i);
        $p_info = $GLOBALS['le']->fetch_assoc();

        $storage=-1;
        $pstorage=$s->get_Dynamic_Price_Merge($pid,substr($begintime,0,10),1,"","",0,1);
        $pstorage=explode(",",$pstorage);
        $pstorage=$pstorage[1];//设置的日库存
        if($pstorage!=-1){
            $storageXml=$s->Dynamic_Storage_Check($p_info['tid'],1,$begintime);
            $storageXml=simplexml_load_string($storageXml);
            $storageXml=(string)$storageXml->Rec->UUXstr;
            $dayStorage=explode("|",$storageXml);
            $dayStorage=$dayStorage[1];//使用的日库存
            $storage=$pstorage-$dayStorage;
        }
        if($p_info['storage']!=-1){
            $storageXml=$s->Dynamic_Storage_Check($p_info['tid'],2,NUll,$p_info['storage_open']);
            $storageXml=simplexml_load_string($storageXml);
            $useStorage=$storageXml->Rec->UUXstr;
            $totalStorage=$p_info['storage']-$useStorage;//剩余总库存
            if(($totalStorage<$storage&&$storage>0)||$storage==-1) $storage=$totalStorage;
        }
        if($storage==-1) $storage="不限";
        return $storage;
    }

    /**
     * 删除价格配置
     *
     * @param $prcid 价格记录表的ID（根据接口获取到的xml数据）
     * @return int
     */
    public function RemoveSPrice($prcid) {
        $str = "DELETE FROM uu_product_price WHERE id={$prcid}";
        if($GLOBALS['le']->query($str)) {
            return 1000;
        }
        return 0;
    }

    /**
     * 同步价格到16u平台
     *
     * @param $pid 票付通PID
     * @param $pft_rflex_id 分销平台关联PID
     * @param $diff_price 差价，单位分
     * @return mixed
     * @Time:2013年12月5日 16:50:04
     * @Update:2013年12月6日 13:48:06
     */
    public function PriceSync($pid, $pft_rflex_id, $diff_price)
    {
        $xml = $this->GetDynamicPrice('', 0, date('Y-m-d'),'',0,1, $pid);
        $lists = simplexml_load_string($xml);
        $soap16u = SoapInit::GetSoapFX();
        $ret = 100;
        foreach($lists as $val) {
            $enddate = (string)$val->UUend_date;
            if($enddate < date('Y-m-d')) continue;
            $rid = (int)$val->UUid;
            $ptype = (int)$val->UUptype;
            $pg = $ptype==1 ? $val->UUs_price:$val->UUn_price;
            $pl = $val->UUl_price;
            $ondays = (string)$val->UUweekdays;
            $startdate = (string)$val->UUstart_date;

            $storage = (int)$val->UUstorage;
            $g_price = $pg + $diff_price;
            $l_price = $pl + $diff_price;

            $ret = $soap16u->In_Dynamic_Price_Merge($pft_rflex_id, $startdate,
                $enddate, $g_price, $l_price, $ptype, 2, $rid, '',
                $ondays, $storage, 11);
//            echo 'pid=',$pid,'rid='.$rid . 'ret=',$ret,'st=',$startdate ,$enddate;
        }
//        echo 'ret=',$ret;
        return $ret;
    }
}